var express = require('express')
var fs = require('fs')
var path = require('path')

// var arr = [
//     { bianhao: '1', bianma: 'ceo', mingchen: '董事长', paixu: '1', zhaungtai: true, time: '2022-11-25 17:00:48', }, { bianhao: '1', bianma: 'ceo', mingchen: '董事长', paixu: '1', zhaungtai: true, time: '2022-11-25 17:00:48', }, { bianhao: '1', bianma: 'ceo', mingchen: '董事长', paixu: '1', zhaungtai: true, time: '2022-11-25 17:00:48', }
// ]


//子路由对象
var userRouter = express.Router()

//分页
userRouter.get('/list', (req, res) => {

    console.log('收到了来自客户端的请求');

    //读取用户数据
    var filepath = path.join(__dirname, '../json/user.json')
    var arr = fs.readFileSync(filepath)
    arr = arr.toString() ? JSON.parse(arr) : []

    var { page, count } = req.query
    var newarr = arr.slice((page - 1) * count, page * count)
    res.send({ code: 200, msg: '请求成功', list: newarr })
})

//搜索
userRouter.get('/search', (req, res) => {

    //读取用户数据
    var filepath = path.join(__dirname, '../json/user.json')
    var arr = fs.readFileSync(filepath)
    arr = arr.toString() ? JSON.parse(arr) : []

    var { searchkey } = req.query
    var newarr = arr.filter((item) => {
        return item.mingchen.includes(searchkey)
    })
    res.send({ code: 200, msg: '搜索成功', list: newarr })
})

//登录
userRouter.post('/login', (req, res) => {

    //读取用户数据
    var filepath = path.join(__dirname, '../json/user.json')
    var arr = fs.readFileSync(filepath)
    arr = arr.toString() ? JSON.parse(arr) : []
    console.log('收到了来自客户端的请求');
    var { mingchen, bianma } = req.body

    var i = arr.findIndex((item) => {
        return item.mingchen == mingchen && item.bianma == bianma
    })

    if (i != -1) {
        res.send({ code: 200, msg: '登陆成功！', userinfo: arr[i] })
    } else {
        res.send({ code: 400, msg: '登陆失败！' })
    }
})

//注册
userRouter.post('/register', (req, res) => {
    //获取注册相关参数
    var { mingchen} = req.body

    //读取users.json文件中的用户数据（读取原有数据）
    var filepath = path.join(__dirname, '../json/user.json')
    var arr = fs.readFileSync(filepath)
    arr = arr.toString() ? JSON.parse(arr) : []

    //判断新用户是否已经存在
    var i = arr.findIndex((item) => {
        return item.mingchen == mingchen
    })
    if (i != -1) {   //用户已存在，注册失败
        res.send({ code: 400, msg: '改手机号已注册，注册失败' })
    } else {
        //添加新用户到user.json中
        arr.push({ ...req.body,bianhao: '1',paixu: '1', zhaungtai: true, time: '2022-11-25 17:00:48'})
        fs.writeFileSync(filepath, JSON.stringify(arr), 'utf-8')
        res.send({ code: 200, msg: '注册成功！' })
    }
})

//导出
module.exports = userRouter